package com.tierstall.client.view;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gwt.core.client.prefetch.RunAsyncCode;
import com.google.gwt.view.client.ListDataProvider;
import com.tierstall.client.view.content.CV_addGroup;
import com.tierstall.client.view.content.CV_addTier;
import com.tierstall.client.view.content.CV_dbFilter;
import com.tierstall.client.view.content.CV_searchResult;
import com.tierstall.client.view.content.CV_showUsers;
import com.tierstall.client.view.main.ContentWidget;
import com.tierstall.client.view.main.ViewConstants;

import com.tierstall.shared.Page;

public class ContentViewManager {

	private final ListDataProvider<ContentWidget> examples = new ListDataProvider<ContentWidget>();
	private final List<RunAsyncCode> splitPoints = new ArrayList<RunAsyncCode>();

	/**
	 * A mapping of history tokens to their associated {@link ContentWidget}.
	 */
	private final Map<Page, ContentWidget> contentToken = new HashMap<Page, ContentWidget>();

	public ContentViewManager(ViewConstants constants) {
		initializeTree(constants);
	}

	public void addExample(ContentWidget example, RunAsyncCode splitPoint) {
		examples.getList().add(example);

		if (splitPoint != null) {
			splitPoints.add(splitPoint);
		}
		contentToken.put(example.getPagename(), example);
	}

	/**
	 * Get the content widget associated with the specified history token.
	 * 
	 * @param token
	 *            the history token
	 * @return the associated {@link ContentWidget}
	 */
	public ContentWidget getContentWidgetForToken(Page token) {
		return contentToken.get(token);
	}

	/**
	 * Initialize the top level categories in the tree.
	 */
	private void initializeTree(ViewConstants constants) {

		// Datenbank

		addExample(new CV_dbFilter(),
				RunAsyncCode.runAsyncCode(CV_dbFilter.class));
		addExample(new CV_addGroup(constants),
				RunAsyncCode.runAsyncCode(CV_addGroup.class));
		addExample(new CV_addTier(),
				RunAsyncCode.runAsyncCode(CV_addTier.class));
		addExample(new CV_searchResult(),
				RunAsyncCode.runAsyncCode(CV_searchResult.class));

		// User
		addExample(new CV_showUsers(constants),
				RunAsyncCode.runAsyncCode(CV_showUsers.class));
	}
}
